package com.android.djlmapp.activity.kuandai.base;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.ForgetPwdActivity;
import com.android.djlmapp.activity.kuandai.web.KuanDaiPayJumpActivity;
import com.android.djlmapp.activity.order.OrderListActivity;
import com.android.djlmapp.activity.recharge.AddMoneyActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.listener.LocationCallBack;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.model.home.LocationInfo;
import com.android.djlmapp.tools.global.Constants;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.MD5Util;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

/**
 * 宽带基类
 */
public class KuanDaiBaseActivity extends BaseActivity {

    public double latitude = 0; // 纬度
    public double longitude = 0; // 经度

    // 判断附加参数是否有值
    public boolean isKdtc = false;

    public boolean isGsqd = false;
    public boolean isFzr = false;
    public boolean isDsf = false;
    public boolean isGdcq = false;
    public boolean isDwhs = false;
    public boolean isKdPhone = false;


    public String gsqdId = "";
    public String dsfId = "";
    public String gdcqId = "";
    public String dwhsId = "";
    public String fzrId = "";


    public String kdtype = ""; // 业务类型
    public String kuandaiAddress = ""; // 报装地址
    public String addressId = ""; // 报装地址id

    // 实名认证返回
    public int phot_lists = 0;
    public String face_image = "";
    public String face_ok = "";
    public String sfz_card = "";
    public String sfz_name = "";
    public String sfzPhoto = "";
    public String bluetoothName = "";
    public String sFlag = "";
    public String sMoney = "";


    public String taocanSpecId = "";
    public String taocanShowInput = ""; // 用来判断单宽带的附加参数需要显示哪些,包含字段就显示,不包含就隐藏
    public String fzrPhoneSub = "";
    public String dkdTvQdmcSub = "";
    public String dkdTvNameSub = "";
    public String dkdTvFzsSub = "";
    public String dkdTvGdcqSub = "";
    public String dkdTvWhsSub = "";
    public String dkdTvBeizhuSub = "";
    public String kuandaiBuchongSub = "";
    public String llTvLxhmSub = "";
    public String dkdTvIptvSnSub = "";
    public String dkdTvGlPhoneSub = "";
    public String dkdTvKuandaiPhoneSub = "";
    public String addressNote = ""; // 地址备注

    public String payamount = ""; // 自由话费


    // 加装参数
    public String jzPhone = ""; // 原有号码

    // 智慧沃家参数
    public String kdPhoneNum = ""; // 自选号码
    public String kdSimNum = ""; // 关联SIM卡

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        kdtype = getIntent().getStringExtra("KDTYPE");
        addressId = getIntent().getStringExtra("ADDRESS_ID");
        addressNote = getIntent().getStringExtra("ADDRESS_NOTE");
        kuandaiAddress = getIntent().getStringExtra("KUANDAI_ADDRESS");

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    /**
     * 提交宽带订单
     */
    private void submitOrder(String pwd, String touchPwd, String touchNum) {
        MyApplication.getInstance().getHttpTools().subDanKuanDaiOrder(taocanSpecId, sfz_card,
                dkdTvIptvSnSub, kuandaiBuchongSub, dkdTvBeizhuSub, dkdTvGlPhoneSub, dkdTvKuandaiPhoneSub,
                llTvLxhmSub, phot_lists, gsqdId, dkdTvQdmcSub, dsfId, dkdTvFzsSub, gdcqId, dkdTvGdcqSub,
                dwhsId, dkdTvWhsSub, addressId, kuandaiAddress, addressNote, fzrId, dkdTvNameSub,
                fzrPhoneSub, pwd, touchPwd, touchNum, longitude + "", latitude + "", jzPhone, kdPhoneNum,
                kdSimNum, payamount, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parseJson(response);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("宽带", "------数据解析异常------" + e.toString());
                            passwordDialog.setState(R.mipmap.pay_er, "支付失败1");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        passwordDialog.setState(R.mipmap.pay_er, "支付失败,网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

    }

    private void parseJson(Response<String> response) {
        Gson gson = new Gson();
        Info info = gson.fromJson(response.body(), Info.class);
        if (info != null) {
            if (TextUtils.isEmpty(info.getMsg())) {
                passwordDialog.setState(R.mipmap.pay_er, "提交失败:" + info.getCode());
                return;
            }
            if (info.getCode() == 200) {
                passwordDialog.setState(R.mipmap.pay_su, "支付成功");
                String ordSn = info.getOrder_sn();

                subTiJiaoBanLi(gson, ordSn);
            } else if (info.getCode() > 7000) {
                // 跳转订单
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());

                // 发送EventBus,关闭宽带首页和地址页
                EventBusUtil.sendEvent(new Event<String>(EventCodes.EventKuanDaiCode.A));
                startActivity(new Intent(KuanDaiBaseActivity.this, OrderListActivity.class));
                finish();

            } else {
                // 提示错误
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());
            }
        } else {
            passwordDialog.setState(R.mipmap.pay_er, "提交返回数据为空");
        }
    }

    /**
     * 提交办理
     *
     * @param gson
     * @param ordSn
     */
    private void subTiJiaoBanLi(Gson gson, String ordSn) {
        MyApplication.getInstance().getHttpTools().kdTiJiaoBanLi(ordSn, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Info subInfo = gson.fromJson(response.body(), Info.class);
                if (subInfo.getCode() == 200) {
                    String webUrl = subInfo.getUrl();
                    // 发送EventBus,关闭宽带首页和地址页
                    EventBusUtil.sendEvent(new Event<String>(EventCodes.EventKuanDaiCode.A));
                    if (!TextUtils.isEmpty(webUrl)) {
                        // 跳转新的web
                        startActivity(new Intent(KuanDaiBaseActivity.this, KuanDaiPayJumpActivity.class)
                                .putExtra("sucUrl", webUrl));
                    } else {
                        // 跳转订单
                        startActivity(new Intent(KuanDaiBaseActivity.this, OrderListActivity.class));
                    }
                    finish();
                } else {
                    passwordDialog.setState(R.mipmap.pay_er, subInfo.getMsg());
                    startActivity(new Intent(KuanDaiBaseActivity.this, OrderListActivity.class));
                    finish();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                passwordDialog.setState(R.mipmap.pay_er, "办理失败,网络或服务器错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }


    //=======================================软键盘=======================================
    private DJLM_PasswordDialog passwordDialog;

    /**
     * 初始化密码键盘
     */
    private void initKeyBord() {
        passwordDialog = new DJLM_PasswordDialog(KuanDaiBaseActivity.this);
        passwordDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, String pwd) {
                passwordDialog.showLoadingView();
                submitOrder(pwd, "", "");
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
                passwordDialog.showLoadingView();
                String touch_pwd = PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, "");
                String num = (System.currentTimeMillis() + "").substring(3);
                String newpwd = MD5Util.MD5("DJLM_TOUCH_PAY" + num +
                        UserInfoUtils.getUserInfoUtilsInstance().getToken() + touch_pwd).toLowerCase();
                submitOrder(Constants.getZhiWenNewPwd(KuanDaiBaseActivity.this),
                        Constants.getZhiWenTouchPwd(KuanDaiBaseActivity.this),
                        Constants.zhiWenNum);
            }

            @Override
            public void onBtnClick(int type) {
                if (type == 1) {
                    //加款按钮点击
                    startActivity(new Intent(KuanDaiBaseActivity.this, AddMoneyActivity.class));
                } else if (type == 2) {
                    //忘记密码按钮点击
                    startActivity(new Intent(KuanDaiBaseActivity.this, ForgetPwdActivity.class));
                }
            }
        });
    }

    /**
     * 弹出自定义输入键盘
     */
    private void showKeyBoard() {
        initKeyBord(); // 初始化密码键盘
        passwordDialog.show(getSupportFragmentManager(), "支付");
        if (PrefUtils.getBoolean(ConstantsValue.ZHIWEN_STATE, false)
                && !TextUtils.isEmpty(PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, ""))) {
            if (passwordDialog.isFingerprintEnable()) {
                passwordDialog.setEnableFinger(true);
            } else {
                passwordDialog.setEnableFinger(false);
            }

        } else {
            passwordDialog.setEnableFinger(false);
        }
        //设置余额
        passwordDialog.setYue(sMoney);
    }


    //=======================================请求定位权限=======================================

    /**
     * 获取位置信息
     */
    public void getLocationPrem() {
        showKeyBoard();
        // 获取经纬度
        try {
            OnceLocationTools locationTools = new OnceLocationTools(KuanDaiBaseActivity.this,
                    new LocationCallBack() {
                        @Override
                        public void successGetLocation(LocationInfo info) {
                            //定位成功
                            latitude = info.getLatitude();
                            longitude = info.getLongitude();
                        }

                        @Override
                        public void error(String error) {
                            latitude = 0.0;
                            longitude = 0.0;
                        }
                    });
            locationTools.startLocation();//开始定位
        } catch (NullPointerException ex) {
            latitude = 0.0;
            longitude = 0.0;
        }
    }
}
